from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from typing import List
from app.db.session import get_session
from app.models.session import Session as SessionModel
from app.models.message import Message as MessageModel
from app.schemas.history import SessionOut, MessageOut

# 创建 router 对象
router = APIRouter(tags=["history"])

# 获取用户所有会话列表
@router.get("/sessions/{user_id}", response_model=List[SessionOut])
async def get_user_sessions(user_id: int, session: AsyncSession = Depends(get_session)):
    result = await session.execute(select(SessionModel).where(SessionModel.user_id == user_id))
    sessions = result.scalars().all()
    return sessions

# 获取会话的消息列表
@router.get("/messages/{session_id}", response_model=List[MessageOut])
async def get_session_messages(session_id: int, session: AsyncSession = Depends(get_session)):
    result = await session.execute(
        select(MessageModel).where(MessageModel.session_id == session_id).order_by(MessageModel.created_at)
    )
    messages = result.scalars().all()
    return messages